/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.map.L1Map;
import l1j.server.server.model.map.L1WorldMap;
import l1j.server.server.storage.CharacterStorage;
import l1j.server.server.storage.mysql.MySqlCharacterStorage;
import l1j.server.server.templates.L1CharName;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

public class CharacterTable {
	private final CharacterStorage _charStorage;

	private static CharacterTable _instance;

	private static Logger _log = Logger.getLogger(CharacterTable.class.getName());

	public static void clearOnlineStatus() {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("UPDATE characters SET OnlineStatus=0");
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
	public static boolean doesCharNameExist(String name) {
		boolean result = true;
		java.sql.Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT account_name FROM characters WHERE char_name=?");
			pstm.setString(1, name);
			rs = pstm.executeQuery();
			result = rs.next();
		} catch (final SQLException e) {
			_log.warning("could not check existing charname:" + e.getMessage());
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		return result;
	}

	public static CharacterTable getInstance() {
		if (_instance == null) {
			_instance = new CharacterTable();
		}
		return _instance;
	}

	public static void saveCharStatus(L1PcInstance pc) {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("UPDATE characters SET OriginalStr= ?"
					+ ", OriginalCon= ?, OriginalDex= ?, OriginalCha= ?"
					+ ", OriginalInt= ?, OriginalWis= ?" + " WHERE objid=?");
			pstm.setInt(1, pc.getBaseStr());
			pstm.setInt(2, pc.getBaseCon());
			pstm.setInt(3, pc.getBaseDex());
			pstm.setInt(4, pc.getBaseCha());
			pstm.setInt(5, pc.getBaseInt());
			pstm.setInt(6, pc.getBaseWis());
			pstm.setInt(7, pc.getId());
			pstm.execute();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public static void saveNewCharStatus(L1PcInstance pc) {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("UPDATE characters SET OriginalStr= ?"
					+ ", OriginalCon= ?, OriginalDex= ?, OriginalCha= ?"
					+ ", OriginalInt= ?, OriginalWis= ?" + " WHERE objid=?");
			pstm.setInt(1, pc.getOriginalStr());
			pstm.setInt(2, pc.getOriginalCon());
			pstm.setInt(3, pc.getOriginalDex());
			pstm.setInt(4, pc.getOriginalCha());
			pstm.setInt(5, pc.getOriginalInt());
			pstm.setInt(6, pc.getOriginalWis());
			pstm.setInt(7, pc.getId());
			pstm.execute();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public static void updateOnlineStatus(final L1PcInstance pc) {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con
					.prepareStatement("UPDATE characters SET OnlineStatus=? WHERE objid=?");
			pstm.setInt(1, pc.getOnlineStatus());
			pstm.setInt(2, pc.getId());
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public static void updatePartnerId(final int targetId) {
		updatePartnerId(targetId, 0);
	}


	public static void updatePartnerId(final int targetId, final int partnerId) {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con
					.prepareStatement("UPDATE characters SET PartnerID=? WHERE objid=?");
			pstm.setInt(1, partnerId);
			pstm.setInt(2, targetId);
			pstm.execute();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public static void updateHellTime(final int objid, final int helltime) {
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("UPDATE characters SET HellTime=? WHERE objid=?");
			pstm.setInt(1, helltime);
			pstm.setInt(2, objid);
			pstm.execute();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	private final Map<String, L1CharName> _charNameList = new ConcurrentHashMap<String, L1CharName>();

	private final Map<Integer, String> _charList = new ConcurrentHashMap<Integer, String>();

	private CharacterTable() {
		this._charStorage = new MySqlCharacterStorage();
	}

	public void deleteCharacter(final String accountName, final String charName)throws Exception {
		// 多分、同期は必要ない
		this._charStorage.deleteCharacter(accountName, charName);
		if (this._charNameList.containsKey(charName)) {
			this._charList.remove(this._charNameList.get(charName).getId());
			this._charNameList.remove(charName);
		}
		_log.finest("deleteCharacter");
	}

	public L1CharName[] getCharNameList() {
		return this._charNameList.values().toArray(new L1CharName[this._charNameList.size()]);
	}

	public String getPcNameById(final int char_id){
		return this._charList.get(char_id);
	}

	public void loadAllCharName() {
		final PerformanceTimer timer = new PerformanceTimer();
		L1CharName cn = null;
		String name = null;
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM characters");
			rs = pstm.executeQuery();
			while (rs.next()) {
				cn = new L1CharName();
				name = rs.getString("char_name");
				cn.setName(name);
				cn.setId(rs.getInt("objid"));
				//opqlo 不允許玩家加入GM為好友
				final int AccessLevel = rs.getInt("AccessLevel");
				if(AccessLevel==200){
					cn.setIsGM(true);
				}else{
					cn.setIsGM(false);
				}
				//opqlo 不允許玩家加入GM為好友
				this._charNameList.put(name, cn);
				this._charList.put(cn.getId(), name);
			}
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		_log.info("載入已用角色名稱資料數量: " + _charNameList.size() + "(" + timer.get() + "ms)");
	}

	public L1PcInstance loadCharacter(final String charName) throws Exception {
		L1PcInstance pc = null;
		try {
			pc = this.restoreCharacter(charName);

			// マップの範囲外ならSKTに移動させる
			final L1Map map = L1WorldMap.getInstance().getMap(pc.getMapId());

			if (!map.isInMap(pc.getX(), pc.getY())) {
				pc.setX(33087);
				pc.setY(33396);
				pc.setMap((short) 4);
			}
			_log.finest("loadCharacter: " + pc.getName());
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		return pc;

	}

	public L1PcInstance restoreCharacter(final String charName) throws Exception {
		final L1PcInstance pc = this._charStorage.loadCharacter(charName);
		return pc;
	}

	public void restoreInventory(L1PcInstance pc) {
		pc.getInventory().loadItems();
		pc.getDwarfInventory().loadItems();
		pc.getDwarfForElfInventory().loadItems();
	}

	public void storeCharacter(final L1PcInstance pc) throws Exception {
		synchronized (pc) {
			this._charStorage.storeCharacter(pc);
			_log.finest("storeCharacter: " + pc.getName());
		}
	}

	public void storeNewCharacter(L1PcInstance pc) throws Exception {
		synchronized (pc) {
			this._charStorage.createCharacter(pc);
			final String name = pc.getName();
			if (!this._charNameList.containsKey(name)) {
				final L1CharName cn = new L1CharName();
				cn.setName(name);
				cn.setId(pc.getId());
				this._charNameList.put(name, cn);
				this._charList.put(pc.getId(), name);
			}
			_log.finest("storeNewCharacter");
		}
	}


	public void UpdateCharName(L1PcInstance pc , String Name){
		final String srcName = pc.getName();
		if (this._charNameList.containsKey(srcName)) {
			this._charList.remove(this._charNameList.get(srcName));
			this._charNameList.remove(srcName);
		}

		final L1CharName cn = new L1CharName();
		cn.setName(Name);
		cn.setId(pc.getId());
		this._charNameList.put(Name, cn);
		this._charList.put(cn.getId(), Name);
	}
	
	/**檢查該名稱是否有使用過**/
	public boolean CheckCharName(final String name){
		return this._charNameList.containsKey(name);
	}

}
